package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.DateUtils;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.Vote;
import com.letv.whatslive.model.convert.VoteConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/6/7.
 */
@Repository
public class VoteDAO extends BaseDAO {
    private final static Logger logger = LoggerFactory.getLogger(VoteDAO.class);

    protected String collectionName = "vote";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 根据查询条件查询所有的投票信息列表
     * @param params
     * @return
     */
    public List<Vote> getAllVoteList(Map<String, Object> params) {
        List<Vote> VoteList = Lists.newArrayList();
        try {
            BasicDBObject queryCondition = getBasicDBObjectByParams(params);
            DBCursor dbCursor = dbCollection.find(queryCondition);
            while (dbCursor.hasNext()) {
                Vote vote = VoteConvert.castDBObjectToVote(dbCursor.next());
                setValueToVote(vote);
                VoteList.add(vote);
            }
        } catch (Exception e) {
            logger.error("getAllVoteList by params error!", e);
        }
        return VoteList;
    }


    /**
     * 根据查询条件查询所有的投票信息列表
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<Vote> getVoteListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<Vote> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Vote vote = VoteConvert.castDBObjectToVote(dbObject);
                setValueToVote(vote);
                result.add(vote);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *根据设备Id获取投票信息
     * @param id
     * @return
     */
    public Vote getVoteById(Long id) {
        BasicDBObject query = new BasicDBObject();
        Vote vote = new Vote();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            vote = VoteConvert.castDBObjectToVote(dbObject);
            setValueToVote(vote);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return vote;
    }

    /**
     * 保存投票信息
     * @param vote
     * @return
     */
    public String saveVote(Vote vote) {
        try {
            vote.setId(getAutoIncrementId());
            DBObject dbo = VoteConvert.castVoteToDBObject(vote);
            WriteResult wr = this.dbCollection.insert(dbo);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }
    public Long countVoteByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 更新投票信息
     * @param vote
     */
    public void updateVote(Vote vote) {
        DBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", vote.getId());
        BasicDBObject setValue = (BasicDBObject)VoteConvert.castVoteToDBObject(vote);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照id倒序排序
            order.append("createTime", -1);
        }
        return order;
    }
    public List<Vote> getVoteListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<Vote> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Vote vote = VoteConvert.castDBObjectToVote(dbObject);
                setValueToVote(vote);
                result.add(vote);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }
    public long insertVote(Vote vote){
        DBObject obj = VoteConvert.castVoteToDBObject(vote);
        return this.insert(obj);
    }

    public void deleteVoteById(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }


    /**
     * 根据查询条件Map获取查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("actId") != null) {
                query.put("actId", ObjectUtils.toLong(params.get("actId")));
            }
            if (params.get("programId") != null) {
                query.put("programId", ObjectUtils.toLong(params.get("programId")));
            }
            if (params.get("userId") != null) {
                query.put("userId", ObjectUtils.toLong(params.get("userId")));
            }
            if (params.get("voteNum") != null) {
                query.put("voteNum", ObjectUtils.toLong(params.get("voteNum")));
            }
            if (params.get("pName") != null) {
                Pattern pattern = Pattern.compile("^.*" + ObjectUtils.toString(params.get("pName")) + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("pName", pattern);
            }
            if (params.get("nickName") != null) {
                Pattern pattern = Pattern.compile("^.*" + ObjectUtils.toString(params.get("nickName")) + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("nickName", pattern);
            }
            if (params.get("pNameOrPid") != null) {
                BasicDBList values = new BasicDBList();
                Pattern pattern = Pattern.compile("^.*" + params.get("pNameOrPid") + ".*$", Pattern.CASE_INSENSITIVE);
                values.add(new BasicDBObject("programId", ObjectUtils.toLong(params.get("pNameOrPid"))));
                values.add(new BasicDBObject("pName", pattern));
                query.put("$or", values);
            }
            if (params.get("nickNameOrUid") != null) {
                BasicDBList values = new BasicDBList();
                Pattern pattern = Pattern.compile("^.*" + params.get("nickNameOrUid") + ".*$", Pattern.CASE_INSENSITIVE);
                values.add(new BasicDBObject("userId", ObjectUtils.toLong(params.get("nickNameOrUid"))));
                values.add(new BasicDBObject("nickName", pattern));
                query.put("$or", values);
            }
        }

        return query;
    }

    private void setValueToVote(Vote vote) {
        vote.setCreateTimeStr(vote.getCreateTime() != null ?
                DateUtils.long2YMDHMS(vote.getCreateTime()):"");
        vote.setUpdateTimeStr(vote.getUpdateTime() != null ?
                DateUtils.long2YMDHMS(vote.getUpdateTime()) : "");

    }
}
